package com.wchen.gdoc.generate.mapping.resolver;


import com.wchen.gdoc.generate.config.ApplicationConfigProvide;
import com.wchen.gdoc.generate.mapping.data.ParamData;
import com.wchen.gdoc.generate.resource.structure.FieldStructure;
import com.wchen.gdoc.generate.resource.structure.ObjectStructure;
import com.wchen.gdoc.generate.util.StructureUtil;

import java.util.*;

/**
 * 自定义类型转换器
 */
public class CustomTypeStructureResolver extends ObjectStructureResolver {


    /**
     * 判断是否支持解析器解析
     *
     * @param classType
     * @return
     */
    @Override
    public Boolean isSupport(String classType) {
        Map<String, List<String>> excludFieldMap = ApplicationConfigProvide.getApplicationConfig().getTargetProjectConfig().getExclusiveFieldMap();
        return excludFieldMap.containsKey(classType);
    }

    /**
     * 参数解析
     *
     * @param objectStructure
     * @return
     */
    @Override
    public ParamData doResolve(ObjectStructure objectStructure) {
        Set<String> configFields = matchDealFields(objectStructure.getType());
        String paramName = StructureUtil.getTypeAlias(objectStructure);
        String commentText = StructureUtil.getCommentText(objectStructure);
        if(ENABLE_DEBUG) {
            LOGGER.info(String.format("自定义类型解析开始: type:%s, name:%s", objectStructure.getType(), objectStructure.getSimpleName()));
        }

        List<ParamData> paramDataChildren = new ArrayList<>();
        if("T".equals(objectStructure.getType())){
            return super.createParamData(paramName, objectStructure.getType(), null, "{}", commentText, Boolean.FALSE);
        }

        for (FieldStructure fieldStructure : objectStructure.getFieldList()) {
            //忽略自定义字段
            if(configFields.contains(fieldStructure.getFieldName())) {
                continue;
            }
            ParamData fieldParamData = super.doResolverChain(fieldStructure);
            paramDataChildren.add(fieldParamData);
        }

        return super.createParamData(paramName, objectStructure.getType(), null, paramDataChildren, commentText, Boolean.TRUE);
    }


    /**
     * 获取匹配的特殊处理字段
     * @param classType
     * @return
     */
    private HashSet<String> matchDealFields(String classType) {
        Map<String, List<String>> exclusiveFieldMap = ApplicationConfigProvide.getApplicationConfig().getTargetProjectConfig().getExclusiveFieldMap();
        return  new HashSet<String>(exclusiveFieldMap.get(classType));
    }
}
